<?php

namespace Frieza\Modules\LightTopic\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\service\admin\LightTopicPrize as sLightTopicPrize;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class LightTopicPrizeController extends Controller
{
    public function index(Content $content, $topicId)
    {
        $list = sLightTopicPrize::getList($topicId);
        $gridModel = new pGridDataModel($list['list'], $list['total']);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->expandFilter();
            $grid->disableFilter();

            $grid->column('id', '奖品id');
            $grid->column('desc', '奖品描述')->display(function () {
                $array = json_decode($this->desc, true);
                if ($array && is_array($array)) {
                    return implode("<br>", $array);
                }
                return '';
            });
            $grid->column('pic_id_url', '奖品图片')->display(function () {
                $picIdUrl = $this->pic_id ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_OP_ORI) : null;
                return '<img style="width:100px;height:100px" src="' . $picIdUrl . '" >';
            });
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('prize_status', '进度')->display(function () {
                $currentTime = date("Y-m-d H:i:s");
                if ($currentTime < $this->start_time) {
                    $status = '未开始';
                } else if ($currentTime > $this->start_time && $currentTime < $this->end_time) {
                    $status = '进行中';
                } else if ($currentTime > $this->end_time) {
                    $status = '已结束';
                }
                return $status;
            });
            $grid->column('admin_id', '操作者')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });
        });

        return $content
            ->header('奖品管理')->description("轻话题id：$topicId")
            ->breadcrumb(
                [
                    'text' => '轻话题列表',
                    'url' => 'LightTopic/index'
                ],
                [
                    'text' => '奖品管理'
                ]
            )
            ->row($listGrid);

    }

    public function edit(Content $content, $topicId, $prizeId = 0)
    {
        $prizeInfo = [];
        if ($prizeId) {
            $prizeInfo = sLightTopicPrize::getInfo($prizeId);
        }

        $form = new Form($prizeInfo);
        $form->hidden('topic_id');
        $form->hidden('id', $prizeId);
        $form->dateTimeRange('start_time', 'end_time', '参与有奖时间')->required();
        $form->textarea('desc', '奖品描述')->required();
        $form->imgUpload('pic_id', '奖品图', true, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI])
            ->setMinImageHeight(296)->setMaxImageHeight(296)->setMinImageWight(590)->setMaxImageWight(590)->help('请上传296（宽） x 590（高）尺寸的图片');

        $form->action("/admin/LightTopic/{$topicId}/lightTopicPrize/save");
        return $content
            ->header('轻话题奖品管理')
            ->breadcrumb(
                [
                    'text' => '轻话题列表',
                    'url' => 'LightTopic/index'
                ],
                [
                    'text' => '奖品管理',
                    'url' => "LightTopic/$topicId/lightTopicPrize"
                ],
                [
                    'text' => '奖品编辑'
                ]
            )
            ->body($form);
    }

    public function save(Request $request, $topicId)
    {
        try {
            $data = $request->all();
            $data['desc'] = json_encode(explode(PHP_EOL, $request['desc']), JSON_UNESCAPED_UNICODE);
            $data['admin_id'] = Admin::user()->id;
            $data['topic_id'] = $topicId;

            if (!$data['pic_id']) {
                throw new \Exception('请上传图片');
            }

            $prizeId = sLightTopicPrize::save($data['id'], $data);
            if ($prizeId) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
                return redirect(url("/admin/LightTopic/{$topicId}/lightTopicPrize"))->with(compact('success'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function delete($topicId, $prizeId)
    {
        $id = sLightTopicPrize::delete($prizeId, Admin::user()->id);
        if ($id) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => '删除失败',
            ]);
        }
    }
}